import Interface
import Play
import Display

import tkinter as tk
from tkinter import messagebox
import json

baseUrl = "http://121.41.112.199:3000"

def requireLikeData():
    global like_list
    try:
        f = open('like_list.json', 'r',encoding="utf-8")
        content = f.read()
        #将读取内容转化为python字典
        like_list = json.loads(content)
    except FileNotFoundError:
        f = open('like_list.json', 'w')
        f.write("")
        f.close()
        like_list = []
    except json.decoder.JSONDecodeError:
        like_list = []

def createFrame():
    #生成主容器
    global mainLikeFrame
    mainLikeFrame = tk.Frame(Interface.app,borderwidth = 1, relief="raised")
    mainLikeFrame.pack(side='left',fill = 'both')
    tk.Label(mainLikeFrame, text="我喜欢").pack(side='top', anchor="w", fill="both")
    tk.Button(mainLikeFrame, text = "一键播放",command = Play.allPlay).pack(side='top',anchor="w")
    tk.Button(mainLikeFrame, text = "选中此板块以使用滚轮",command = lambda type = "like":Display.freshScro(type)).pack(side='top',anchor="w")

    # 创建画布和滚动条，Canvas,Scrollbar放置在主窗口上
    global likeCanvas
    likeCanvas = tk.Canvas(master=mainLikeFrame)
    likeCanvas.pack(side='left', fill='both', expand=True)
    global likeScro
    likeScro = tk.Scrollbar(master=mainLikeFrame)
    likeScro.pack(side='right', fill='y')
    
    requireLikeData()
    Display.display("like",like_list)

def add(song):
    global songs

    try:
        f = open('like_list.json', 'r',encoding="utf-8")
        content = f.read()
        #将读取内容转化为字典
        songs = json.loads(content)
    except json.decoder.JSONDecodeError:
        songs = []

    #判断是否已经存在
    if not song in songs:
        songs.append(song)
        messagebox.showinfo("提示","添加成功")
    else:
        messagebox.showerror("错误","歌曲已存在")

    #保存数据到本地
    #通过json.dumps()把dict降级为字符串
    temp = json.dumps(songs,indent = 4,ensure_ascii=False)
    save_json = open('like_list.json', 'w',encoding='utf-8')
    save_json.write(temp)
    save_json.close()

    requireLikeData()
    Display.display("like",like_list)

def delete(song):
    global songs

    try:
        f = open('like_list.json', 'r',encoding="utf-8")
        content = f.read()
        #将读取内容转化为字典
        songs = json.loads(content)
    except json.decoder.JSONDecodeError:
        songs = []

    while song in songs:
        songs.remove(song)
        messagebox.showinfo("提示","删除成功")


    #保存数据到本地
    #通过json.dumps()把dict降级为字符串
    temp = json.dumps(songs,indent = 4,ensure_ascii=False)
    save_json = open('like_list.json', 'w',encoding='utf-8')
    save_json.write(temp)
    save_json.close()

    requireLikeData()
    Display.display("like",like_list)